//
//  AddCourseNoteViewController.m
//  TeacherNet
//
//  Created by slz on 2017/12/13.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "AddCourseNoteViewController.h"
#import <YYText.h>
#import <IQKeyboardManager.h>
#import "WJPopoverViewController.h"

@implementation AddCourseHourTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self){
        _titleLabel = [UILabel new];
        _titleLabel.textColor = kDark_TextColor_Default;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.fontSize = 14;
        [self.contentView addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.contentView);
        }];
    }
    return self;
}

@end

@implementation AddCourseHourListModel
+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"list" : [AddCourseHourModel class]
             };
}
+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"list" : @"hourList"
             };
}
@end

@implementation AddCourseHourModel
+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"hourId" : @"id",
             @"hourTitle":@"title"
             };
}
@end


@interface AddCourseNoteViewController ()<YYTextKeyboardObserver,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIButton *sendButton;
@property (nonatomic,strong)YYTextView * textView;
@property (nonatomic,strong)WJPopoverViewController *rightPopView;
@property (nonatomic,strong) UITableView *popTableView;
@property (nonatomic,strong) AddCourseHourListModel *listModel;
@property (weak, nonatomic) IBOutlet UISwitch *shareSwitch;
@property (weak, nonatomic) IBOutlet UILabel *seletcedLabel;
@property (nonatomic,copy)NSString * selectedCourseId;
@end

@implementation AddCourseNoteViewController

- (instancetype)init {
    self = [super init];
    [[YYTextKeyboardManager defaultManager] addObserver:self];
    return self;
}

- (void)dealloc {
    [[YYTextKeyboardManager defaultManager] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.showNavigationBar = YES;
    [self setControllerTitle:@"添加笔记"];
    UIBarButtonItem * backItem = [UIBarButtonItem itemWithImage:@"back_icon" selectImage:@"" addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    [self initSubView];
    [self requestCourseList];
    // Do any additional setup after loading the view from its nib.
}


- (UITableView *)popTableView {
    if(_popTableView == nil) {
        _popTableView = [[UITableView alloc] init];
        _popTableView.frame = CGRectMake(0, 0, kScreenWidth - 110, 200);
        _popTableView.backgroundColor = [UIColor whiteColor];
        _popTableView.delegate = self;
        _popTableView.dataSource = self;
        _popTableView.bounces = NO;
        _popTableView.rowHeight = 40;
    }
    return _popTableView;
}


- (void)requestCourseList
{
    [BaseHttpTool get:kAPI_COURSE_CLASS_HOUR_LIST params:@{@"class_id":self.classId,@"course_id":self.couseId,@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid} success:^(id responseObj) {
        NSDictionary * dict = [[MFWJson jsonWithObject:responseObj] toDic];
        AddCourseHourListModel * listModel = [AddCourseHourListModel yy_modelWithDictionary:dict];
        _listModel = listModel;
        
        NSArray * arr = listModel.list;
        if (arr && arr.count > 0){
            AddCourseHourModel * model = listModel.list[0];
            self.seletcedLabel.text = model.hourTitle;
            self.selectedCourseId = model.hourId;
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_textView becomeFirstResponder];
}

- (void)initSubView
{
    @weakify(self);
    _textView = [YYTextView new];
    _textView.origin = CGPointMake(11, 64);
    _textView.size = CGSizeMake(kScreenWidth - 22, kScreenHeight - 208);
    _textView.font = [UIFont systemFontOfSize:15];
    _textView.placeholderText = @"记点什么吧...";
    _textView.placeholderFont = [UIFont systemFontOfSize:15];
    _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    _textView.showsVerticalScrollIndicator = NO;
    _textView.alwaysBounceVertical = YES;
    [self.view addSubview:_textView];
    
    _sendButton =[UIButton buttonWithType:UIButtonTypeCustom];
    _sendButton.size = CGSizeMake(kScreenWidth - 40, 50);
    _sendButton.bottom = self.view.bottom;
    _sendButton.left = 20;
    [_sendButton setTitle:@"添   加" forState:UIControlStateNormal];
    _sendButton.backgroundColor = kLoginGreenColor;
    [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @strongify(self);
        [self sendNoteAction];
    }];
    [self.view addSubview:_sendButton];
}

- (void)sendNoteAction{
    NSString * noteContent = self.textView.text;
    if (noteContent.length <=0){
        [self.view showTip:@"请输入笔记内容~"];
        return;
    }
    @weakify(self);
    NSString * isShare = self.shareSwitch.isOn ? @"1" : @"0";
    NSString * userId = [MFWSdkEnvironment sharedInstance].userInfo.uid;
    
    [SVProgressHUD showWithStatus:@"笔记发送中..."];
    [BaseHttpTool get:kAPI_COURSE_ADD_NOTE params:@{@"user_id":userId,
                                                    @"course_id":self.couseId,
                                                    @"course_hour_id":self.selectedCourseId,
                                                    @"is_share":isShare,
                                                    @"note_content":self.textView.text}
    success:^(id responseObj)
    {
        BOOL sendSuccess = [[MFWJson jsonWithObject:responseObj] booleanValueForKey:@"msg"];
        if (sendSuccess){
            [SVProgressHUD showSuccessWithStatus:@"发送成功~"];
            if ([weak_self.delegate respondsToSelector:@selector(addNoteWithResult:andIsShare:)]){
                [weak_self.delegate addNoteWithResult:YES andIsShare:isShare];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"发送失败"];
        }
        
    } failure:^(NSError *error)
    {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


#pragma mark - YYKeyboardManager
- (void)keyboardChangedWithTransition:(YYTextKeyboardTransition)transition{
    CGRect toFrame = [[YYTextKeyboardManager defaultManager] convertRect:transition.toFrame toView:self.view];
    if (transition.animationDuration == 0) {
        _sendButton.bottom = toFrame.origin.y;
        NSInteger textViewHeight = _sendButton.top - _textView.top;
        _textView.height = textViewHeight - 11;
    } else {
        [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption | UIViewAnimationOptionBeginFromCurrentState animations:^{
            _sendButton.bottom = toFrame.origin.y;
            NSInteger textViewHeight = _sendButton.top - _textView.top;
            _textView.height = textViewHeight - 11;
        } completion:NULL];
    }
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * resuerIndentifier = @"AddCourseHourTableViewCell";
    AddCourseHourTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:resuerIndentifier];
    if (!cell){
        cell = [[AddCourseHourTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resuerIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    AddCourseHourModel * model = _listModel.list[indexPath.row];
    cell.titleLabel.text = model.hourTitle;
    return cell;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listModel.list.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddCourseHourModel * model = _listModel.list[indexPath.row];
    self.seletcedLabel.text = model.hourTitle;
    self.selectedCourseId = model.hourId;
    [WJPopoverViewController dissPopoverViewWithAnimation:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (IBAction)dropAction:(id)sender WithEvent:(UIEvent *)event{
    self.rightPopView = [[WJPopoverViewController alloc] initWithShowView:self.popTableView];
    [self.rightPopView showPopoverWithTouch:event animation:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
